﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Sinacor.Infra.Service.Security.Authorization;
using Sinacor.Infra.Service.Security;

namespace Sinacor.Infra.Service.Logic
{
    public class SinacorBusinessLogic
    {
        /// <summary>
        /// Executa uma Action
        /// </summary>
        /// <param name="actionName">Nome da Action</param>
        /// <param name="parameters">Parâmetros de Execução da Action</param>
        /// <returns></returns>
        protected object ExecuteAction(string actionName, params object[] parameters)
        {
            ActionConfig config;
            string method;

            config = ActionConfigReader.GetInstance().Read(actionName);

            if (config.IsKernelPlusAction)
            {
                if (this.HaskKernelPlusLicense())
                    method = config.Method;
                else
                    method = config.AlternativeMethod;
            }
            else
                method = config.AlternativeMethod;
                     

            if (string.IsNullOrEmpty(method))
                return null;
            else
                return this.GetType().GetMethod(method, BindingFlags.Instance | BindingFlags.Public).Invoke(this, parameters);

        }

        /// <summary>
        /// Verifica licença Kernel Plus
        /// </summary>
        /// <returns></returns>
        private bool HaskKernelPlusLicense()
        {
            LicensingManager licensingManager = LicensingManager.GetInstance();
            
            Company company = new Company() { Id = AuthorizationContext.Current.CompanyId, Name = AuthorizationContext.Current.CompanyName, CGC = AuthorizationContext.Current.CompanyCGC };

            return licensingManager.ValidateKernelPlus(company);
        }
    }
}
